package com.william.jdbcplus.core.toolkit;

import com.william.jdbcplus.core.toolkit.json.JsonUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 使用reflect进行转换
 */
public class MapTransformUtils {

    public static <T> T mapToEntity(Map<String, Object> map, Class<T> entityClass) {
        if (map == null) {
            return null;
        }

        if (ClassUtil.isElementType(entityClass)) {
            Object obj = null;
            Collection<Object> collection = map.values();
            if (collection.size() > 0) {
                obj = collection.iterator().next();
            } else {
                obj = null;
            }
            T result = JsonUtil.map(obj, entityClass);
            return result;
        } else {
            T result = JsonUtil.map(map, entityClass);
            return result;
        }
    }

    public static <T> List<T> mapToEntityList(List<Map<String, Object>> mapList, Class<T> entityClass) {
        List<T> result = new ArrayList<T>();
        if (mapList == null || mapList.size() == 0) {
            return result;
        }

        if (ClassUtil.isElementType(entityClass)) {
            List<Object> objectList = mapList.stream().map(e -> {
                if (e.values().size() > 0) {
                    return e.values().iterator().next();
                } else {
                    return null;
                }
            }).collect(Collectors.toList());
            result = JsonUtil.mapList(objectList, entityClass);
            return result;
        } else {
            result = JsonUtil.mapList(mapList, entityClass);
            return result;
        }
    }

}
